package org.restql;

import org.mortbay.jetty.Server;
import org.mortbay.jetty.servlet.Context;
import org.mortbay.jetty.servlet.ServletHolder;
import org.restql.webapp.RestQLServlet;

public class Launcher {

	private static String DEFAULT_ROOT = "/restql";
	private static int DEFAULT_PORT = 8080;

	private String root = DEFAULT_ROOT;
	private int port = DEFAULT_PORT;

	public static void main(String[] args) throws Exception {
		new Launcher(args);
	}

	public Launcher(String args[]) throws Exception {
		if (parseCommandLineArgs(args)) {
			Server server = new Server(port);
			Context context = new Context(server, root, Context.SESSIONS);
			context.addServlet("jsp.intro_jsp", "/intro.jsp");
			context.addServlet("jsp.config_jsp", "/config.jsp");
			
			RestQLServlet restQLServlet = null;
			if (args.length > 0) {
				//restQLServlet = new RestQLServlet(args[0]);
			} else {
				restQLServlet = new RestQLServlet();
			}
			context.addServlet(new ServletHolder(restQLServlet), "/*");
			server.start();
		}
	}

	private boolean parseCommandLineArgs(String[] args) {
		boolean proceed = true;

		try {
			for (int i = 0; i < args.length; i++) {
				if (args[i].equals("-p")) {
					port = Integer.parseInt(args[i+1]);
				}
				if (args[i].equals("-r")) {
					root = args[i+1];
				}
				if (args[i].equals("-h") || args[i].equals("-?") || args[i].equals("--help")) {
					proceed = false;
					printCommandLineOptions();
				}
			}
		} catch (Exception e) {
			proceed = false;
			printCommandLineOptions();
		}

		return proceed;
	}

	private static void printCommandLineOptions() {
		System.out.println("RestQL Standalone Server, powered by JETTY!");
		System.out.println("-------------------------------------------");
		System.out.println("Command Line Options:");
		System.out.println("  -p port     Port number to start Jetty on. Default: 8080.");
		System.out.println("  -r root     Path to root the server on. Default: /restql");
		System.out.println();
	}

}
